// pages/order/order.js
const personal = require('../../api/personal.js')
const order = require('../../api/order.js')
const product = require('../../api/product.js')
const addressApi = require('../../api/address.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    totalNum: 0,
    totalMoney: 0,
    arr: [],
    num: 0,
    sum: 0,
    user: {},
    pay_type: 0,
    send_type: 0,
    order_id: 0,
    id: '',
    address: {},
    address_id: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getAddress()
    this.getSelectedCarts()
  },
  // 选择送货方式
  selectSendType() {
    let that = this
    wx.showModal({
      title: '请选择送货方式',
      content: '',
      confirmText: '送货上门',
      cancelText: '自取',
      success(res) {
        if (res.confirm) {
          that.setData({
            send_type: 0
          })
        } else if (res.cancel) {
          that.setData({
            send_type: 1
          })
        }
      },
      fail(res) {
        console.log(res)
      }
    })
  },
  // 获取勾选地址
  getAddress() {
    let token = wx.getStorageSync('token')
    personal.getUserInfo(token).then(res => {
      this.setData({
        user: res.data.data
      })
      let address = wx.getStorageSync('address' + this.data.user.id) || []
      if (address.length > 0) {
        address.forEach(value => {
          if (value.isSelected) {
            this.setData({
              address: value
            })
            let data = value
            data.address_detail_id = Math.floor(Math.random()*99999).toString() 
            addressApi.addAddress(data).then(res => {
              if(res.data.code == 0) {
                addressApi.getAddress(data.address_detail_id).then(res => {
                  let id = res.data.data[0].id
                  this.setData({
                    address_id: id
                  })
                })
              }
            })
          }else {
            this.setData({
              address: {}
            })
          }
        })
      }
    })
  },
  // 获取已勾选商品
  getSelectedCarts() {
    let token = wx.getStorageSync('token')
    personal.getUserInfo(token).then(res => {
      this.setData({
        user: res.data.data
      })
      let cart = wx.getStorageSync('cart' + this.data.user.id) || []
      this.setData({
        arr: [],
        num: 0,
        sum: 0
      })
      if (this.data.id) {
        cart.forEach(value => {
          if (value.id == this.data.id) {
            this.data.arr.push(value)
            this.data.num = value.count
            this.data.sum = value.price * value.count
          }
        })
        this.setData({
          arr: this.data.arr,
          totalMoney: this.data.sum.toFixed(2),
          totalNum: this.data.num
        })
      } else {
        cart.forEach(value => {
          if (value.isSelect) {
            this.data.arr.push(value)
            this.data.num += value.count
            this.data.sum += value.price * value.count
          }
        })
        this.setData({
          arr: this.data.arr,
          totalMoney: this.data.sum.toFixed(2),
          totalNum: this.data.num
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // 选择地址
  toSelectAddress() {
    wx.navigateTo({
      url: '../personal/address/address',
    })
  },
  // 提交订单
  onSubmit() {
    let that = this
    if (JSON.stringify(this.data.address) == "{}") {
      wx.showToast({
        title: '地址不能为空',
        icon: 'none'
      })
      return
    }
    if (this.data.arr.length > 0) {
      let orderids = []
      let count = 0
      let inventory = 0
      let data2 = {}
      this.data.arr.forEach(value => {
        let order_id = Math.floor(Math.random(111, 199) * 10000000)
        let data = value
        data.send_type = this.data.send_type
        data.address_id = this.data.address_id
        data.pay_type = this.data.pay_type
        data.order_id = this.data.order_id
        data.product_id = value.id
        data.total = value.count * value.price
        data.status = 0,
          data.count = value.count,
          data.common_user_id = this.data.user.id,
          data.order_id = order_id
        orderids.push(order_id)
        order.addOrder(data).then(res => {
          if (res.data.code == 0) {
            wx.showToast({
              title: '提交成功',
            })
            let cart = wx.getStorageSync('cart' + this.data.user.id)
            cart.forEach((value, index) => {
              if (value.isSelect) {
                cart.splice(index, 1)
              }
            })
            wx.setStorageSync('cart' + this.data.user.id, cart)
            count = parseInt(value.count)
            inventory = parseInt(value.inventory) - count
            data2.inventory = inventory
            data2.sale_count = count
            product.updateInventory(value.id, data2).then(res => {
              if (res.data.code == 0) {
                console.log('商品库存发生变化')
                app.setNum()
              }
            })
          }
        })
      })
      wx.redirectTo({
        url: '../order/orderpay/orderpay?ids=' + orderids,
        success() {
          wx.showLoading({
            title: '正在跳转支付',
          })
        }
      })
    }
  }
})